/*
 * RestTemplateConfig.java
 * Copyright 2025 Churan Tech, all rights reserved.
 * Churan PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package com.churan.ai.mcp.server.weather.stdio.config;

import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.util.Timeout;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * Function:
 *
 * @author churan
 * @date: 2025年4月23日
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        // 创建支持 Gzip 的 HttpClient
        final HttpClient httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(Timeout.ofSeconds(5))
                        .setResponseTimeout(Timeout.ofSeconds(10))
                        .build())
                .addResponseInterceptorFirst(this::addGzipHeader)
                .build();
        HttpComponentsClientHttpRequestFactory factory =
                new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(factory);
    }

    private void addGzipHeader(HttpResponse httpResponse, EntityDetails entityDetails, HttpContext httpContext) {
        if (!httpResponse.containsHeader("Accept-Encoding")) {
            httpResponse.addHeader("Accept-Encoding", "gzip");
        }
    }
}
